package com.demo.view;

import com.demo.controller.BackWardListener;
import com.demo.controller.CardsHandler;
import com.demo.controller.MoveCardListener;
import com.demo.controller.MoveSolution;
import com.demo.model.Board;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyListener;

public class GameWindow extends JFrame {
    public static int WIDTH = 400;
    public static int HEIGHT = 640;

    private static final GameWindow instance = new GameWindow();

    private GameWindow() {
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);
        setLocationRelativeTo(null);

        KeyListener keyListener = MoveCardListener.getInstance();
        addKeyListener(keyListener);
    }

    public static void loadGUI() {
        // 布局管理器通过设置FlowLayout的垂直间距达到子组件的居中...
        LayoutManager layoutManager = new FlowLayout(
                FlowLayout.CENTER,
                5,
                (HEIGHT - instance.getInsets().top * 2 - MainViewPanel.HEIGHT) / 2
        );
        instance.setLayout(layoutManager);

        // 设置背景色
        instance.getContentPane().setBackground(Color.decode("#84a2ba"));
        // 主面板载入
        instance.add(MainViewPanel.getInstance());
        instance.setVisible(true);
    }

    public static void restartGame() {
        Board.getInstance().reset();
        CardsHandler.getInstance().randomCard();
        BackWardListener.getInstance().clear();
        CardsView.getInstance().repaint();
        instance.requestFocus();
    }

    public static void checkIfGameOver() {
        if (!MoveSolution.isGameOver()) {
            return;
        }
        Object[] options = {"restart", "back"};
        int option = JOptionPane.showOptionDialog(GameWindow.getInstance(),
                "restart or try the last",
                "info",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.WARNING_MESSAGE,
                null,
                options,
                "restart");

        if (option == 0) {
            GameWindow.restartGame();
        } else if (option == 1) {
            BackWardListener.getInstance().back();
        }
    }

    public static GameWindow getInstance() {
        return instance;
    }
}

